//
//  Utilities.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/6/11.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "Utilities.h"

@implementation Utilities

+ (NSDictionary *)dictionaryWithJsonString:(id)jsonD{
    if (jsonD == nil) {
        return nil;
    }
    
    NSData *jsonData = nil;
    if ([jsonD isKindOfClass:[NSString class]]){
        jsonData = [jsonD dataUsingEncoding:NSUTF8StringEncoding];
    }else if ([jsonD isKindOfClass:[NSData class]]){
        jsonData = jsonD;
    }else if([jsonD isKindOfClass:[NSDictionary class]]){
        NSDictionary *nonullDict = [self nullDic:jsonD];
        return nonullDict;
    }
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    dic = [self nullDic:dic];
    return dic;
}

//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
    if ([myObj isKindOfClass:[NSDictionary class]])
    {
        return [self nullDic:myObj];
    }
    else if([myObj isKindOfClass:[NSArray class]])
    {
        return [self nullArr:myObj];
    }
    else if([myObj isKindOfClass:[NSString class]])
    {
        return [self stringToString:myObj];
    }
    else if([myObj isKindOfClass:[NSNull class]])
    {
        return [self nullToString];
    }
    else
    {
        return myObj;
    }
}

//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
    if ([myDic isKindOfClass:[NSDictionary class]]) {
        NSArray *keyArr = [myDic allKeys];
        NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
        for (int i = 0; i < keyArr.count; i ++)
        {
            id obj = [myDic objectForKey:keyArr[i]];
            obj = [self changeType:obj];
            [resDic setObject:obj forKey:keyArr[i]];
        }
        return resDic;
    }else {
        return @{};
    }
    
}
//将NSDictionary中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
    if ([myArr isKindOfClass:[NSArray class]]) {
        NSMutableArray *resArr = [[NSMutableArray alloc] init];
        for (int i = 0; i < myArr.count; i ++)
        {
            id obj = myArr[i];
            obj = [self changeType:obj];
            [resArr addObject:obj];
        }
        return resArr;
    }else {
        return @[];
    }
    
}
//将NSString类型的原路返回
//过滤掉诡异的"null"和"(null)"字符串
+(NSString *)stringToString:(NSString *)string
{
    if ([string isEqualToString:@"null"] || [string isEqualToString:@"(null)"]) {
        return @"";
    }else{
        return string;
    }
}
//将Null类型的项目转化成@""
+(NSString *)nullToString
{
    return @"";
}

@end
